﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BO;
using UIControls;
using BrightIdeasSoftware;
using UI.Core;
namespace UI
{
    public partial class TrxnImportForm : ToolFormBase
    {
        public TrxnImportForm()
        {
            InitializeComponent();
        }
        DataTable GetTemplateTable()
        {
            var dt = new DataTable();

            var list = FieldHelper.cnName.GetAllColumns();

            foreach (var item in list)
                dt.Columns.Add(item);
            return dt;
        }


        /// <summary>
        /// 导入线程
        /// </summary>
        BackgroundWorker worker;
        /// <summary>
        /// excel中记录总数
        /// </summary>
        private int totalRowsCount;

        /// <summary>
        /// 导入的记录总数
        /// </summary>
        private int importRowsCount;

        /// <summary>
        /// 导入列表
        /// </summary>
        BindingList<Billing> BillingDataList;

        void InitWorker()
        {
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            myProgressBar.Maximum = totalRowsCount;

        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            myProgressBar.Value = (int)(e.ProgressPercentage * totalRowsCount * 0.01);

        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            setEnable(true);
            myProgressBar.Value = totalRowsCount;
            MessageBox.Show(string.Format("Excel表中记录数为 {0} 条，导入记录 {1} 条。", totalRowsCount, importRowsCount));

        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (BillingDataList == null)
                return;
            int cnt = 0;
            importRowsCount = 0;
            BillingList blist =new BillingList();
            foreach (var obj in BillingDataList)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                var per = (int)(100.0 * cnt / totalRowsCount);
                worker.ReportProgress(per);
             
                var entity = obj as Billing;
                entity.CreateTime = DateTime.Now;
                entity.LastModifyTime = DateTime.Now;
                blist.Add(entity);
               
                cnt++;
                importRowsCount++;
            
            }
            blist.Save();
        }
        private bool MutiSheetMode
        {
            get { return cbAll.Checked; }
        }

        void setEnable(bool enabled)
        {
            btnImport.Enabled = enabled;
            this.btnSelectFile.Enabled = enabled;
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            try
            {

                btnSelectFile.Enabled = false;
              Cursor = Cursors.WaitCursor;
                totalRowsCount = 0;
                BillingDataList = new BindingList<Billing>();
                var openFileDlg = new OpenFileDialog();
                if (openFileDlg.ShowDialog(this) != DialogResult.OK)
                    return;
                excel = new ExcelAdapter(openFileDlg.FileName);
                txtFilePath.Text = openFileDlg.FileName;

                if (MutiSheetMode)
                {
                    MutiSelect();
                }
                else
                {
                    SingleSelect();
                }
                BindGrid();
            }
            catch (ExceptionEx ex)
            {
                ExcptionHandler.ShowExcption(ex);

            }
            finally
            {
                btnSelectFile.Enabled = true;
              Cursor = Cursors.Default;
            }

        }
        ExcelAdapter excel;

        void MutiSelect()
        {
            excel.openConnection();
            var ds = excel.readAllEntireSheet();
            excel.closeConnection();

            foreach (DataTable dt in ds.Tables)
            {
                if (VarifyTable(dt))
                {
                    var n1 = totalRowsCount;
                    GenerateDataList(dt);
                    ShowMsg(string.Format("{0}\t数据\t{1} \t条", dt.TableName, totalRowsCount - n1));
                }
            }
        }
        void SingleSelect()
        {

            excel.openConnection();
            var dt = excel.readEntireSheet();
            excel.closeConnection();
            if (dt == null)
                return;
            if (VarifyTable(dt) == false)
            {
                MessageBox.Show("所选文件与模板不相符,请更改.", "错误");
                return;
            }
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("所选文件中没有数据,请更改.", "提示");
                return;
            }
            GenerateDataList(dt);
        }

        void GenerateDataList(DataTable dt)
        {

            foreach (DataRow row in dt.Rows)
            {
                try
                {
                    if (row[0] is DBNull)
                        return;
                    var obj = new Billing();
                  
                    obj.CenterName = row[FieldHelper.cnName.Center].ToString();
                    obj.DepartmentName = row[FieldHelper.cnName.Department].ToString();
                    obj.StaffName = row[FieldHelper.cnName.Staff].ToString();

                    obj.CustomerName = row[FieldHelper.cnName.Customer].ToString();

                    obj.ProductGroupName = row[FieldHelper.cnName.ProductGroup].ToString();
                    obj.ProductName = row[FieldHelper.cnName.Product].ToString();

                    obj.Remark = row[FieldHelper.cnName.Remark].ToString();
                    obj.CRM_OrderNo = row[FieldHelper.cnName.CRM_OrderNo].ToString();

                    obj.Amount = Convert.ToDouble(row[FieldHelper.cnName.Amount]);
                    obj.IsNewCustomer = row[FieldHelper.cnName.IsNewCustomer].ToString()=="是"?true:false;
                    int n = -1;
                    int.TryParse(row[FieldHelper.cnName.Date].ToString(), out n);

                    if (n >= 40913)
                    {
                        var dn = n - 40913;
                        var d0 = new DateTime(2012, 1, 5);
                        var d1 = d0.AddDays(dn);
                        obj.TransDate = d1;
                    }
                    else
                    {

                        obj.TransDate = DateTime.Parse(row[FieldHelper.cnName.Date].ToString()).Date;
                    }
                    if (!MutiSheetMode)
                        obj.CompanyName = row[FieldHelper.cnName.Company].ToString();
                    else
                        obj.CompanyName = dt.TableName;

                    BillingDataList.Add(obj);
                }
                catch
                {
                }


            }
            totalRowsCount = BillingDataList.Count;


        }

        void BindGrid()
        {
            SetupGird();
            //var dt = new DataTable();
            //new BO.Core.ObjectAdapter().Fill(dt, BillingDataList);
            //BindingSource dataSource = new BindingSource(dt, null);
            myGrid.SetObjects(BillingDataList);
            totalRowsCount=BillingDataList.Count;
            ShowMsg(string.Format("所选文件的第一个Sheet中共有{0}条正确数据", totalRowsCount));

        }

        void ShowMsg(string message)
        {
            txtMessage.Text += message + Environment.NewLine;
        }

        bool VarifyTable(DataTable sourceTable)
        {
            var templateTable = GetTemplateTable();

            foreach (DataColumn col in templateTable.Columns)
            {
                if (sourceTable.Columns.IndexOf(col.ColumnName) < 0)
                {
                    if (MutiSheetMode)
                    {
                        if (col.ColumnName == FieldHelper.cnName.Company
                            || col.ColumnName == "编号"
                            )
                            continue;
                    }
                    return false;
                }

            }
            return true;
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (btnImport.Enabled == false)
                return;
            setEnable(false);
            InitWorker();
            worker.RunWorkerAsync();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            worker.CancelAsync();
        }

        private void btnExportTemplate_Click(object sender, EventArgs e)
        {
            myGrid.UseFilterIndicator = true;
            var dt = GetTemplateTable();
            var excel = new ExcelAdapter();
            excel.SaveExcel(dt, "", "业绩明细模板", "销售业绩明细表");
        }


        void SetupGird()
        {
            var cols = new List<OLVColumn>();

            cols.Add(new OLVColumn("编号", "ID") { IsEditable = false, Width = 50 });
            var cDate = new OLVColumn(FieldHelper.cnName.Date, "TransDate");
            cDate.Width = 110;
            cDate.AspectToStringFormat = "{0:d}";
            cDate.ClusteringStrategy = new DateTimeClusteringStrategy();
            cols.Add(cDate);
            cols.Add(new OLVColumn(FieldHelper.cnName.Company, "CompanyName") { Width = 60 });
            cols.Add(new OLVColumn(FieldHelper.cnName.Center, "CenterName") { Width = 110 });
            cols.Add(new OLVColumn(FieldHelper.cnName.Department, "DepartmentName") { Width = 110 });
            cols.Add(new OLVColumn(FieldHelper.cnName.Staff, "StaffName") { Width = 60 });
            cols.Add(new OLVColumn(FieldHelper.cnName.ProductGroup, "ProductGroupName") { Width = 110 });
            cols.Add(new OLVColumn(FieldHelper.cnName.Product, "ProductName") { Width = 150 });
            var cAmount = new OLVColumn(FieldHelper.cnName.Amount, "Amount");
            cAmount.Width = 80;
            cols.Add(cAmount);
            cols.Add(
                new OLVColumn(FieldHelper.cnName.IsNewCustomer, "IsNewCustomer")
                {
                    Width = 60,
                    AspectToStringConverter =
                    new AspectToStringConverterDelegate(item => (bool)item == true ? "是" : "否")
                }
             );
            cols.Add(new OLVColumn(FieldHelper.cnName.Remark, "Remark") { Width = 100 });
            cols.Add(new OLVColumn(FieldHelper.cnName.Customer, "CustomerName") { Width = 300 });


            var grid = myGrid;


            grid.AllColumns.AddRange(cols);


            grid.Columns.AddRange(cols.ToArray());

            grid.ShowFilterMenuOnRightClick = true;

           grid.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.None;
            grid.GridLines = true;
        }

        private void TrxnImportForm_Load(object sender, EventArgs e)
        {
            // InitGird();
        }

        private void txtCompany_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
